<template>
  <div>
    <div id="chart" ref="chart" style="height: 400px"></div>
    <div id="chart1" ref="chart1" style="height: 400px"></div>
  </div>
</template>

<script>
// import echarts from '../../echarts';
export default {
  name: 'Dashboard',
  data() {
    return {
      arr: [],
    };
  },

  // 生命周期 初始化  需要进一步理解
  mounted() {
    this.getOption();
  },

  // mounted() {
  //   this.set();
  // },
  methods: {
    getOption() {
      let arr = [];
      this.$http.get('/blogs').then((res) => {
        // console.log(res);

        let a = 0;
        let b = 0;
        let c = 0;
        for (let i = 0; i < res.result.length; i++) {
          if (res.result[i].category_name == 'webgis') {
            a++;
          } else if (res.result[i].category_name == '倾斜摄影') {
            b++;
          } else if (res.result[i].category_name == '数据处理') {
            c++;
          }
        }
        arr = [a, b, c];

        this.arr = arr;
        // console.log(this.arr);
        // console.log(this.arr);
        // return arr;
        // console.log(arr);
        this.set();
      });
    },
    set() {
      const chart = this.$refs.chart;
      if (chart) {
        // 1.实例化对象
        const myChart = this.$echarts.init(chart);
        // 2.指定配置项和数据
        const option = {
          title: { text: 'Column Chart' },
          tooltip: {},
          xAxis: {
            data: ['webgis', '倾斜摄影', '数据处理'],
          },
          yAxis: {},
          series: [
            {
              name: '数量',
              type: 'bar',
              data: this.arr,
            },
          ],
        };
        // 3.把配置项给实例对象
        myChart.setOption(option);
        // 4.让图表跟随屏幕自适应
        window.addEventListener('resize', function () {
          myChart.resize();
        });
      }
      const chart1 = this.$refs.chart1;
      if (chart1) {
        // 1.实例化对象
        const myChart = this.$echarts.init(chart1);
        // 2.指定配置项和数据
        const option = {
          title: { text: 'Column Chart', left: 'center' },
          tooltip: { trigger: 'item' },
          // 图例
          legend: {
            orient: 'vertical',
            left: 'left',
          },

          series: [
            {
              name: '数量',
              type: 'pie',
              data: [
                { value: this.arr[0], name: 'webgis' },
                { value: this.arr[1], name: '倾斜摄影' },
                { value: this.arr[2], name: '数据处理' },
              ],
            },
          ],
        };
        // 3.把配置项给实例对象
        myChart.setOption(option);
        // 4.让图表跟随屏幕自适应
        window.addEventListener('resize', function () {
          myChart.resize();
        });
      }
      // this.$on('hook:destroyed', () => {
      //   window.removeEventListener('resize', function () {
      //     myChart.resize();
      //   });
      // });
    },
  },
};
</script>

<style></style>
